<?php

namespace App;

use Illuminate\Support\Facades\Auth;
use App\Http\Requests\UserUpRequest;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use DB;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password','photo','introduce','roles_id','partid','displayname'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public static function getAllInfo()
    {
        $users = DB::table('users')
            ->join('roles', 'roles_id', '=', 'roles.id')
            ->select('users.id','users.name', 'users.active', 'roles.name as rname','roles_id')
            ->where('users.active','0')
            ->where('users.partid',Auth::user()->partid)
            ->orderBy('users.id')
            ->paginate(10);
        return $users;
    }

    public static function getPermission($roles_id)
    {
        $users = DB::table('users')
            ->select('permission_ids')
            ->join('roles', 'roles_id', '=', 'roles.id')
            ->where('roles_id', '=', $roles_id)
            ->first();
        $arr = explode(',',$users->permission_ids);
        $arrs = '';
        for ($i=0;$i<sizeof($arr);$i++){
            $permisssion = DB::table('permissions')
                ->select('name')
                ->where('id', '=', $arr[$i])
                ->first();
            $arrs[] = $permisssion->name;
        }
        return $arrs;
    }

    public static function hasname($id,$name){
        $user = new self();
        return $user->where('name',$name)->whereNotIn('id',[$id])->first();
    }

    public static function hasemail($id,$email){
        $user = new self();
        return $user->where('email',$email)->whereNotIn('id',[$id])->first();
    }

    public static function hasuser($uid){
        $user = new self();
        $rel = $user->where('id',$uid)->first();
        return ((Auth::user()->partid)==$rel->partid);
    }

    public function role()
    {
        return $this->belongsTo('App\Models\Role','roles_id');
    }


    public static function upvaladitor(Requsest $request){
        $rel = self::hasname($request->all()['id'],$request->all()['name']);
        if($rel) return back()->with('errors','用户名已存在');
        $rel = self::hasname($request->all()['id'],$request->all()['email']);
        if($rel)return back()->with('errors','邮箱已存在');
        dd($request->all());
    }

}

// self::hasname
// $user->where('id','!=',$id)->get()